import { Injectable, UseFilters } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { clone, equals, isEmpty, isNil } from 'ramda';
import { GroupChatRecord } from 'src/chat-record/entities/group-chat-record.entity';
import { UserChatRecord } from 'src/chat-record/entities/user-chat-record.entity';
import { ChatUser } from 'src/chat_user/entities/chat_user.entity';
import { ChatUserFriend } from 'src/chat_user_friends/entities/chat_user_friend.entity';
import { ChatUserGroup } from 'src/chat_user_group/entities/chat_user_group.entity';
import { GroupChat } from 'src/group-chat/entities/group-chat.entity';
import { HttpExceptionFilter } from 'src/http-exception.filter';
import { throwHttp } from 'src/utlis';
import { Connection, Repository } from 'typeorm';
import { CreateHistorySessionDto, DeleteHistorySessionDto, GetHistorySessionDto, GgetHistorySessionInfoDto, UpdateDoNotDisturbDto, UpdateLatestNewsDto } from './dto/history-session.dto';
import { HistorySession } from './entities/history-session.entities';
const selectList = [
    "historySession.id",
    "historySession.userId",
    "historySession.createDate",
    "historySession.updateDate",
    "historySession.latestNewsId",
    "historySession.historicalUserSessionsId",
    "historySession.doNotDisturb",
    "friends.id",
    "friends.username",
    "friends.account",
    "friends.headimgurl",
    "friends.signature",
    "friends.sex",
    "friends.age",
    "friends.createDate",
    "friends.login_date",
    "chatUserFriend",
]
@Injectable()
export class HistorySessionService {
    constructor(
        @InjectRepository(HistorySession)
        private historySessionRepository: Repository<HistorySession>,
        private readonly connection: Connection,
    ) { }
    @UseFilters(new HttpExceptionFilter())
    async getHistorySession(params: GetHistorySessionDto) {
        try {
            const { userId } = params

            const data = await this.connection.createQueryBuilder(HistorySession, 'historySession')
                // 查询好友信息
                .leftJoinAndMapOne(
                    'historySession.chatUserFriend',
                    ChatUserFriend,
                    'chatUserFriend',
                    `chatUserFriend.userId = historySession.userId 
                    AND 
                    chatUserFriend.friendsId = historySession.historicalUserSessionsId AND chatUserFriend.status = :status
                    `, { status: '1' }
                )
                .leftJoinAndMapOne('historySession.friends', ChatUser, 'friends', 'friends.id = chatUserFriend.friendsId AND friends.del = :del', { del: 1 })
                .select(selectList)
                // .leftJoinAndMapOne('historySession.latestNews', UserChatRecord, 'latestNews', 'latestNews.id = chatUserFriend.latestNewsId')
                // 查询群聊信息
                .leftJoinAndMapOne(
                    'historySession.chatUserGroup',
                    ChatUserGroup, 'chatUserGroup',
                    'chatUserGroup.group_id = historySession.historicalUserSessionsId AND chatUserGroup.userId = historySession.userId AND chatUserGroup.is_join = :is_join',
                    { is_join: 1 }
                )
                .leftJoinAndMapOne('historySession.groupChat', GroupChat, 'groupChat', 'groupChat.group_id = chatUserGroup.group_id')
                // 获取群聊成员
                .leftJoinAndMapMany(
                    'userGroup', ChatUserGroup,
                    'userGroup',
                    'chatUserGroup.group_id = userGroup.group_id',
                    {})
                // 查询群聊成员信息
                .leftJoinAndMapMany(
                    'chatUserGroup.groupMembers', ChatUser,
                    'groupMembers',
                    'userGroup.userId = groupMembers.id',
                    {})
                // 最新消息有用户好友表与群聊表中查找，不在历史会话中查找
                .leftJoinAndMapOne('historySession.userChatlatestNews', UserChatRecord, 'userChatlatestNews', 'userChatlatestNews.id = chatUserFriend.latestNewsId')
                .leftJoinAndMapOne('historySession.groupChatlatestNews', GroupChatRecord, 'groupChatlatestNews', 'groupChatlatestNews.id = groupChat.latestNewsId')
                // 群聊最新消息增加用户信息
                .leftJoinAndMapOne('groupChatlatestNews.user', ChatUser, 'user', 'user.id = groupChatlatestNews.userId')
                .where("historySession.userId = :userId", { userId })
                .orderBy({ 'userChatlatestNews.createDate': 'DESC' })
                .orderBy({ 'groupChatlatestNews.createDate': 'DESC' })
                .getMany();

            return data.map((item: any) => {
                const latestNews = clone(item.userChatlatestNews) || clone(item.groupChatlatestNews)
                delete item.userChatlatestNews
                delete item.groupChatlatestNews
                return {
                    ...item,
                    latestNews
                }
            })
        } catch (error) {
            throwHttp(error.message)
        }
    }
    // 创建历史会话
    @UseFilters(new HttpExceptionFilter())
    async createHistorySession(params: CreateHistorySessionDto) {
        try {
            const { userId, historicalUserSessionsId } = params
            const data = await this.historySessionRepository.findOne({
                where: { userId, historicalUserSessionsId },
            })
            if (!isNil(data)) {
                return data
            }
            const historySession = new HistorySession()
            historySession.userId = userId
            historySession.historicalUserSessionsId = historicalUserSessionsId
            const result = await this.historySessionRepository.manager.save(historySession)
            if (!isEmpty(result)) {
                return result
            }
            throwHttp('创建消息会话失败')
        } catch (error) {
            throwHttp(error.message)
        }
    }
    // // 更新聊天记录ID
    // @UseFilters(new HttpExceptionFilter())
    // async updateLatestNews(params: UpdateLatestNewsDto, userChatRecord: UserChatRecord | GroupChatRecord) {
    //     try {
    //         const { historicalUserSessionsId, userId } = params
    //         await this.getHistorySessionInfo({ historicalUserSessionsId, userId })
    //         // 更新用户
    //         const data = await this.historySessionRepository
    //             .createQueryBuilder()
    //             .update(HistorySession)
    //             .set({ latestNewsId: userChatRecord.id, latestNews: userChatRecord })
    //             .where({ historicalUserSessionsId, userId })
    //             .execute();
    //         if (data.affected) {
    //             return data
    //         }
    //         throwHttp('更新失败')
    //     } catch (error) {
    //         throwHttp(error.message)
    //     }
    // }
    // 删除历史会话
    @UseFilters(new HttpExceptionFilter())
    async deleteHistorySession(params: DeleteHistorySessionDto) {
        try {
            const { userId, historicalUserSessionsId, id } = params
            const data = await this.getHistorySessionInfo({ userId, historicalUserSessionsId, id })
            await this.historySessionRepository.remove(data);
            return '删除成功';
        } catch (error) {
            throwHttp(error.message)
        }
    }
    @UseFilters(new HttpExceptionFilter())
    async getHistorySessionInfo(parmas: GgetHistorySessionInfoDto): Promise<HistorySession> {
        try {
            const data = await this.historySessionRepository.findOne({
                where: parmas,
            })
            if (isNil(data)) {
                throwHttp('找不到历史会话')
                return
            }
            return data
        } catch (error) {
            throwHttp(error.message)
        }
    }
    /**
   * 消息免打扰
   * @param {UpdateDoNotDisturbDto} params 
   * @returns 
   */
    @UseFilters(new HttpExceptionFilter())
    async updateDoNotDisturb(params: UpdateDoNotDisturbDto) {
        try {
            const { userId, historicalUserSessionsId, doNotDisturb } = params
            // 验证当前好友信息是否存在
            await this.getHistorySessionInfo({ userId, historicalUserSessionsId })
            // 更新用户
            await this.historySessionRepository
                .createQueryBuilder()
                .update(HistorySession)
                .set({ doNotDisturb })
                .where({ userId, historicalUserSessionsId })
                .execute();
            // 更新好友信息
            return equals(String(doNotDisturb), '0') ? '免打扰开启成功' : '开启新消息提示'
        } catch (error) {
            console.log(error.message);
            throwHttp(error.message)
        }
    }
}
